package com.mf.basic.services;

import cn.dev33.satoken.stp.StpUtil;
import com.mf.basic.entity.DtoPermission;
import com.mf.basic.entity.DtoRolePermission;
import com.mf.basic.enums.EnumBaseParams;
import com.mf.basic.exceptions.MyException;
import com.mf.basic.mapper.MapperRolePermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Luke on 2025/3/7 17:06.
 */
@Service
@Transactional
public class ServiceRolePermission extends ServiceImpl<MapperRolePermission, DtoRolePermission> implements BaseService<DtoRolePermission>{

    @Override
    public LambdaQueryWrapper<DtoRolePermission> fillParams(Map<String, Object> params) {
        return null;
    }

    @Resource
    private ServiceRole serviceRole;
    @Resource
    private ServicePermission servicePermission;

    /**
     * 添加角色权限关联信息
     * @param roleId 角色ID
     * @param permissionIds 权限IDs
     */
    public synchronized void doAdd(Long roleId, String permissionIds) {
        //验证角色ID是否合法
        serviceRole.findCheckById(Math.toIntExact(roleId), true);
        //查询用户IDs信息, 防止无效的用户ID
        Set<Integer> permissionIdSet;
        try {
            permissionIdSet = idsToSet(permissionIds);
        }catch (Exception e){
            throw new MyException("权限IDs("+permissionIds+")错误, 请检查");
        }
        List<DtoPermission> permissionList = servicePermission.getBaseMapper().selectBatchIds(permissionIdSet);
        Assert.state(permissionList.size() == permissionIdSet.size(), "权限IDs信息错误, 请检查");
        //删除角色下的旧的权限关联信息
        LambdaQueryWrapper<DtoRolePermission> qw = loadQw();
        qw.eq(DtoRolePermission::getRoleId, roleId);
        List<DtoRolePermission> delList = this.list(qw);
        if(!CollectionUtils.isEmpty(delList)){
            this.removeBatchByIds(delList);
        }
        //添加新的角色权限关联信息
        List<DtoRolePermission> addList = new ArrayList<>();
        String douser = (String) StpUtil.getSession().get(EnumBaseParams.douser.name());
        for(DtoPermission permission : permissionList){
            addList.add(new DtoRolePermission()
                    .setPermissionId(permission.getId())
                    .setRoleId(roleId)
                    .setDouser(douser));
        }
        this.saveBatch(addList);
    }

}
